package java_option.audio_a011.audio;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

/**
 * 音频播放
 * 
 * @author java_option
 * @date 2020-10-31
 */
public class AudioPlay {
	private List<String> audios = new ArrayList<>();

	private Clip clip;
//
	private Stack<PlayItem> playStack = new Stack<>();

	class PlayItem {
		int index;
		long microseconds;
	}

	public AudioPlay(String... audio) {
		audios.addAll(Arrays.asList(audio));
	}

	public void addFile(String wavFile) {
		audios.add(0, wavFile);
		clip = null;//
	}

	/**
	 * @param microSeconds 微秒
	 */
	public void onStart(int index, long microSeconds) {
//
		if (playStack.isEmpty() || playStack.peek().index != index) {
//
			for (int i = 0; i < playStack.size(); i++) {
				if (playStack.get(i).index == index) {
					playStack.remove(i);
				}
			}
			PlayItem item = new PlayItem();
			item.index = index;
			item.microseconds = microSeconds;
			playStack.push(item);
//
			clip = null;
		}

		PlayItem topItem = playStack.peek();
		if (clip == null) {
			try {
				String file = audios.get(topItem.index);
				AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(file).getAbsoluteFile());
				clip = AudioSystem.getClip();
				clip.open(audioInputStream);
			} catch (Exception ex) {
				System.out.println("Error with playing sound.");
				ex.printStackTrace();
			}
		}
		clip.setMicrosecondPosition(microSeconds);
		clip.start();
	}

	public void onPause() {
		playStack.peek().microseconds = clip.getMicrosecondPosition();
		clip.stop();
	}

	public void onResume() {
		clip.start();
	}

	public void onStop() {
		clip.stop();
		clip.close();
		clip = null;
	}

}
